package com.chen.aiagent.tools;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Locale;

/**
 * 日期时间工具类
 * 提供各种时间日期相关的功能
 */
@Component
public class DateTimeTool {

    @Tool(description = "Get current date and time in specified format")
    public String getCurrentDateTime(
            @ToolParam(description = "Date time format (e.g., yyyy-MM-dd HH:mm:ss, yyyy/MM/dd, MM/dd/yyyy)") String format
    ) {
        try {
            // 使用LocalDateTimeUtil获得更好的性能
            return LocalDateTimeUtil.format(LocalDateTime.now(), format);
        } catch (Exception e) {
            return "Error formatting date: " + e.getMessage() + ". Available formats: yyyy-MM-dd HH:mm:ss, yyyy/MM/dd, MM/dd/yyyy, etc.";
        }
    }

    @Tool(description = "Get current date in yyyy-MM-dd format")
    public String getCurrentDate() {
        return LocalDateTimeUtil.format(LocalDateTime.now(), DatePattern.NORM_DATE_PATTERN);
    }

    @Tool(description = "Get current time in HH:mm:ss format")
    public String getCurrentTime() {
        return LocalDateTimeUtil.format(LocalDateTime.now(), DatePattern.NORM_TIME_PATTERN);
    }

    @Tool(description = "Get current date and time in standard format (yyyy-MM-dd HH:mm:ss)")
    public String getCurrentDateTimeStandard() {
        return LocalDateTimeUtil.format(LocalDateTime.now(), DatePattern.NORM_DATETIME_PATTERN);
    }

    @Tool(description = "Get current timestamp in milliseconds")
    public String getCurrentTimestamp() {
        return String.valueOf(DateUtil.current());
    }

    @Tool(description = "Get current date and time in Chinese format")
    public String getCurrentDateTimeChinese() {
        return LocalDateTimeUtil.format(LocalDateTime.now(), "yyyy年MM月dd日 HH时mm分ss秒");
    }

    @Tool(description = "Get current date in Chinese format")
    public String getCurrentDateChinese() {
        return LocalDateTimeUtil.format(LocalDateTime.now(), "yyyy年MM月dd日");
    }

    @Tool(description = "Get current time in Chinese format")
    public String getCurrentTimeChinese() {
        return LocalDateTimeUtil.format(LocalDateTime.now(), "HH时mm分ss秒");
    }

    @Tool(description = "Get current day of week")
    public String getCurrentDayOfWeek() {
        return LocalDateTime.now().getDayOfWeek().getDisplayName(java.time.format.TextStyle.FULL, Locale.CHINESE);
    }

    @Tool(description = "Get current day of week in English")
    public String getCurrentDayOfWeekEnglish() {
        return LocalDateTime.now().getDayOfWeek().getDisplayName(java.time.format.TextStyle.FULL, Locale.ENGLISH);
    }

    @Tool(description = "Get current month name")
    public String getCurrentMonthName() {
        return LocalDateTimeUtil.format(LocalDateTime.now(), "M月");
    }

    @Tool(description = "Get current month name in English")
    public String getCurrentMonthNameEnglish() {
        return LocalDateTimeUtil.format(LocalDateTime.now(), "MMMM");
    }

    @Tool(description = "Get current year")
    public String getCurrentYear() {
        return String.valueOf(LocalDateTime.now().getYear());
    }

    @Tool(description = "Get current month number")
    public String getCurrentMonth() {
        return String.valueOf(LocalDateTime.now().getMonthValue());
    }

    @Tool(description = "Get current day of month")
    public String getCurrentDay() {
        return String.valueOf(LocalDateTime.now().getDayOfMonth());
    }

    @Tool(description = "Get current hour")
    public String getCurrentHour() {
        return String.valueOf(LocalDateTime.now().getHour());
    }

    @Tool(description = "Get current minute")
    public String getCurrentMinute() {
        return String.valueOf(LocalDateTime.now().getMinute());
    }

    @Tool(description = "Get current second")
    public String getCurrentSecond() {
        return String.valueOf(LocalDateTime.now().getSecond());
    }

    @Tool(description = "Get date and time after specified duration")
    public String getDateTimeAfter(
            @ToolParam(description = "Number of units") long amount,
            @ToolParam(description = "Time unit (DAYS, HOURS, MINUTES, SECONDS)") String unit
    ) {
        try {
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime future = null;

            switch (unit.toUpperCase()) {
                case "DAYS":
                    future = LocalDateTimeUtil.offset(now, amount, java.time.temporal.ChronoUnit.DAYS);
                    break;
                case "HOURS":
                    future = LocalDateTimeUtil.offset(now, amount, java.time.temporal.ChronoUnit.HOURS);
                    break;
                case "MINUTES":
                    future = LocalDateTimeUtil.offset(now, amount, java.time.temporal.ChronoUnit.MINUTES);
                    break;
                case "SECONDS":
                    future = LocalDateTimeUtil.offset(now, amount, java.time.temporal.ChronoUnit.SECONDS);
                    break;
                default:
                    return "Error: Invalid time unit. Available units: DAYS, HOURS, MINUTES, SECONDS";
            }

            return LocalDateTimeUtil.format(future, DatePattern.NORM_DATETIME_PATTERN);
        } catch (Exception e) {
            return "Error calculating future date: " + e.getMessage() + ". Available units: DAYS, HOURS, MINUTES, SECONDS";
        }
    }

    @Tool(description = "Get date and time before specified duration")
    public String getDateTimeBefore(
            @ToolParam(description = "Number of units") long amount,
            @ToolParam(description = "Time unit (DAYS, HOURS, MINUTES, SECONDS)") String unit
    ) {
        try {
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime past = null;

            switch (unit.toUpperCase()) {
                case "DAYS":
                    past = LocalDateTimeUtil.offset(now, -amount, java.time.temporal.ChronoUnit.DAYS);
                    break;
                case "HOURS":
                    past = LocalDateTimeUtil.offset(now, -amount, java.time.temporal.ChronoUnit.HOURS);
                    break;
                case "MINUTES":
                    past = LocalDateTimeUtil.offset(now, -amount, java.time.temporal.ChronoUnit.MINUTES);
                    break;
                case "SECONDS":
                    past = LocalDateTimeUtil.offset(now, -amount, java.time.temporal.ChronoUnit.SECONDS);
                    break;
                default:
                    return "Error: Invalid time unit. Available units: DAYS, HOURS, MINUTES, SECONDS";
            }

            return LocalDateTimeUtil.format(past, DatePattern.NORM_DATETIME_PATTERN);
        } catch (Exception e) {
            return "Error calculating past date: " + e.getMessage() + ". Available units: DAYS, HOURS, MINUTES, SECONDS";
        }
    }

    @Tool(description = "Get time difference between two dates")
    public String getTimeDifference(
            @ToolParam(description = "First date (yyyy-MM-dd HH:mm:ss)") String date1,
            @ToolParam(description = "Second date (yyyy-MM-dd HH:mm:ss)") String date2,
            @ToolParam(description = "Time unit (DAYS, HOURS, MINUTES, SECONDS)") String unit
    ) {
        try {
            LocalDateTime firstDateTime = LocalDateTimeUtil.parse(date1);
            LocalDateTime secondDateTime = LocalDateTimeUtil.parse(date2);

            long difference = 0;
            switch (unit.toUpperCase()) {
                case "DAYS":
                    difference = LocalDateTimeUtil.between(firstDateTime, secondDateTime, java.time.temporal.ChronoUnit.DAYS);
                    break;
                case "HOURS":
                    difference = LocalDateTimeUtil.between(firstDateTime, secondDateTime, java.time.temporal.ChronoUnit.HOURS);
                    break;
                case "MINUTES":
                    difference = LocalDateTimeUtil.between(firstDateTime, secondDateTime, java.time.temporal.ChronoUnit.MINUTES);
                    break;
                case "SECONDS":
                    difference = LocalDateTimeUtil.between(firstDateTime, secondDateTime, java.time.temporal.ChronoUnit.SECONDS);
                    break;
                default:
                    return "Error: Invalid time unit. Available units: DAYS, HOURS, MINUTES, SECONDS";
            }

            return "Time difference: " + Math.abs(difference) + " " + unit.toLowerCase();
        } catch (Exception e) {
            return "Error calculating time difference: " + e.getMessage();
        }
    }

    @Tool(description = "Check if given date is today")
    public String isToday(
            @ToolParam(description = "Date to check (yyyy-MM-dd)") String date
    ) {
        try {
            LocalDate checkDate = LocalDate.parse(date);
            LocalDate today = LocalDate.now();
            return checkDate.equals(today) ? "Yes, it's today" : "No, it's not today";
        } catch (Exception e) {
            return "Error checking date: " + e.getMessage();
        }
    }

    @Tool(description = "Get current timezone")
    public String getCurrentTimezone() {
        return java.util.TimeZone.getDefault().getID();
    }

    @Tool(description = "Get current date and time in specific timezone")
    public String getCurrentDateTimeInTimezone(
            @ToolParam(description = "Timezone ID (e.g., Asia/Shanghai, America/New_York, Europe/London)") String timezoneId
    ) {
        try {
            LocalDateTime now = LocalDateTime.now();
            return LocalDateTimeUtil.format(now, DatePattern.NORM_DATETIME_PATTERN) + " " + timezoneId;
        } catch (Exception e) {
            return "Error getting timezone time: " + e.getMessage() + ". Available timezones: Asia/Shanghai, America/New_York, Europe/London, etc.";
        }
    }

    @Tool(description = "Get current week number of the year")
    public String getCurrentWeekNumber() {
        return String.valueOf(LocalDateTime.now().get(java.time.temporal.WeekFields.ISO.weekOfYear()));
    }

    @Tool(description = "Get current quarter of the year")
    public String getCurrentQuarter() {
        int month = LocalDateTime.now().getMonthValue();
        int quarter = (month - 1) / 3 + 1;
        return "Q" + quarter;
    }

    @Tool(description = "Get current season")
    public String getCurrentSeason() {
        int month = LocalDateTime.now().getMonthValue();
        if (month >= 3 && month <= 5) {
            return "Spring";
        } else if (month >= 6 && month <= 8) {
            return "Summer";
        } else if (month >= 9 && month <= 11) {
            return "Autumn";
        } else {
            return "Winter";
        }
    }

    @Tool(description = "Get current season in Chinese")
    public String getCurrentSeasonChinese() {
        int month = LocalDateTime.now().getMonthValue();
        if (month >= 3 && month <= 5) {
            return "春季";
        } else if (month >= 6 && month <= 8) {
            return "夏季";
        } else if (month >= 9 && month <= 11) {
            return "秋季";
        } else {
            return "冬季";
        }
    }

    @Tool(description = "Get comprehensive current date and time information")
    public String getComprehensiveDateTimeInfo() {
        LocalDateTime now = LocalDateTime.now();

        StringBuilder info = new StringBuilder();
        info.append("=== 当前时间信息 ===\n");
        info.append("标准格式: ").append(LocalDateTimeUtil.format(now, DatePattern.NORM_DATETIME_PATTERN)).append("\n");
        info.append("中文格式: ").append(LocalDateTimeUtil.format(now, "yyyy年MM月dd日 HH时mm分ss秒")).append("\n");
        info.append("日期: ").append(LocalDateTimeUtil.format(now, DatePattern.NORM_DATE_PATTERN)).append("\n");
        info.append("时间: ").append(LocalDateTimeUtil.format(now, DatePattern.NORM_TIME_PATTERN)).append("\n");
        info.append("星期: ").append(now.getDayOfWeek().getDisplayName(java.time.format.TextStyle.FULL, Locale.CHINESE)).append("\n");
        info.append("月份: ").append(LocalDateTimeUtil.format(now, "M月")).append("\n");
        info.append("年份: ").append(now.getYear()).append("\n");
        info.append("季度: ").append(getCurrentQuarter()).append("\n");
        info.append("季节: ").append(getCurrentSeasonChinese()).append("\n");
        info.append("时区: ").append(java.util.TimeZone.getDefault().getID()).append("\n");
        info.append("时间戳: ").append(DateUtil.current()).append("\n");

        return info.toString();
    }
} 